package com.sso.gateway.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Desc:
 *
 * @author: keen
 * Date: 2020-06-23
 * Time: 21:21
 */
// @WebFilter(filterName = "jwtFilter", urlPatterns = "/*")
public class JwtFilter implements Filter {

    private final static String SIGN_IN_URL = "/auth/signIn";
    private final static String AUTHORIZATION_PREFIX = "Bearer ";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        System.out.println("JwtFilter");
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        String requestURI = httpServletRequest.getRequestURI();
        if (requestURI.contains(SIGN_IN_URL)) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            String jti = getJtiFromCookie(httpServletRequest);
            if (StringUtils.isBlank(jti)) {
                accessDenied(httpServletResponse, "请登录");
                return;
            }
            String token = getTokenFromCache(jti);
            if (StringUtils.isBlank(token)) {
                accessDenied(httpServletResponse, "请登录");
                return;
            }
            if (!checkToken(httpServletRequest, token)) {
                accessDenied(httpServletResponse, "令牌错误");
                return;
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    private boolean checkToken(HttpServletRequest httpServletRequest, String token) {
        String authorization = httpServletRequest.getHeader("Authorization");
        if (StringUtils.isBlank(authorization) ||
                !authorization.startsWith(AUTHORIZATION_PREFIX)) {
            return false;
        }
        return token.equals(StringUtils.substringAfter(authorization, AUTHORIZATION_PREFIX));
    }

    private String getTokenFromCache(String jti) {
        String redisKey = "user_token:" + jti;
        String token = stringRedisTemplate.opsForValue().get(redisKey);
        if (StringUtils.isNotBlank(token)) {
            try {
                Map tokenMap = objectMapper.readValue(token, Map.class);
                token = (String) tokenMap.get("access_token");
            } catch (IOException e) {
                return "";
            }
        }
        return token;
    }

    private String getJtiFromCookie(HttpServletRequest request) {
        String jwt = "";
        Cookie[] cookies = request.getCookies();
        if (ArrayUtils.isNotEmpty(cookies)) {
            Cookie uid = Arrays.stream(cookies)
                    .filter(cookie -> cookie.getName().equals("uid"))
                    .findFirst().orElse(null);
            if (uid != null) {
                jwt = uid.getValue();
            }
        }

        return jwt;
    }

    private void accessDenied(HttpServletResponse response, String message) throws IOException {
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(message);
    }
}
